let gulp = require('gulp');
let path = require('path');
let watch = require('gulp-watch');
let webpack = require('webpack');
let gutil = require('gulp-util');
let bs = require("browser-sync").create();

let wpStream = null,
    initEntry = require('./webpack.common.js');
    initWebpackConfig = require('./webpack.config.js');

let wpStdout = ( err, stats) => {
    if ( err) {
        throw new gutil.PluginError('webpack:runing', err);
    }
    gutil.log('[webpack:runing]', stats.toString({
        chunks: false, // Makes the build much quieter
        colors: true
    }));
}

//  webpack
let wpDevStream = () => {
    let config = initWebpackConfig('dev');
        config.entry = initEntry();
    return webpack( config).watch( {}, ( err, stats) => {
        wpStdout( err, stats);
        //  add change event
        bs.reload();
    });
}

gulp.task( 'koaServer', cb => {
    cb();
});

gulp.task( 'wp:bulid', cb => {
    webpack( initWebpackConfig('prod')).run( ( err, stats) => {
        wpStdout( err, stats);
        cb();
    });
});

gulp.task( 'wp:dev', () => {
    return wpStream = wpDevStream();
});

gulp.task( 'build', [ 'wp:bulid'], () => {
    gutil.log('[webpack:bulid]', 'bulid done!');
});

gulp.task( 'dev', [ 'koaServer', 'wp:dev'], () => {
    bs.init({
        proxy: "http://localhost:3000"
    });

    watch( './src/views/**/*.html', vinyl => {
        bs.reload();
    })

    //  监控入口文件目录，当添加或删除入口文件重启 `webapck --watch`
    watch( './src/resource/js/ui/*.js', { events: [ 'add', 'unlink']}, vinyl => {
        //  重启 webpack （重启时会重新计算入口的文件）
        wpStream.close( () => {
            gutil.log('[webpack:dev]', 'webpack watching reset.');
        })
        wpStream = wpDevStream();
    });
});

gulp.task( 'default', ['dev'], () => {

});